package net.dgg.zz.production.org.service;

import com.alibaba.fastjson.JSONObject;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.org.entity.OrganizationEntity;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.dao.OrderDao;
import net.dgg.zz.common.dao.ProductDao;
import net.dgg.zz.common.entity.CustomerRecord;
import net.dgg.zz.common.entity.Node;
import net.dgg.zz.common.entity.Order;
import net.dgg.zz.common.entity.Product;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.service.FlowService;
import net.dgg.zz.common.systemRecord.dao.SystemRecordDao;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.MQMessageSendUtil;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.credential.baseCredential.dao.BaseCredentialDao;
import net.dgg.zz.credential.baseCredential.service.BaseCredentialService;
import net.dgg.zz.credential.certificateProduct.service.CertificateProductService;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.ProductTimeStatus;
import net.dgg.zz.production.inProcess.dao.AssistantDao;
import net.dgg.zz.production.inProcess.dao.ProductNodeFlowDao;
import net.dgg.zz.production.inProcess.dao.ProductOrderDao;
import net.dgg.zz.production.inProcess.dao.ProductTimeStatusDao;
import net.dgg.zz.production.inProcess.entity.Assistant;
import net.dgg.zz.production.inProcess.entity.ProductNodeFlow;
import net.dgg.zz.production.vo.ChargeBackOrderVo;
import net.dgg.zz.production.vo.OrderDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

@Service
public class OrgOrderService {

    @Autowired
    private SessionManager sessionmanager;
    @Autowired
    private DesUtil desUtil;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private ProductNodeFlowDao nodeFlowDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private ProductTimeStatusDao producttimestatusdao;
    @Autowired
    private CmsService cmsservice;
    @Autowired
    private SystemRecordDao systemRecordDao;
    @Autowired
    private OrganizationManager organizationManager;
    @Autowired
    private AssistantDao assistantDao;
    @Autowired
    private CertificateProductService CertificateProductService;
    @Autowired
    private BaseCredentialService baseCredentialService;
    @Autowired
    private BaseCredentialDao baseCredentialDao;
    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private CommonService commonService;
    @Autowired
    private FlowService flowService;


    /**
     * 查询事业部订单列表
     *
     * @param param
     * @return
     */
    public List<Map> orgOrderWithPage(Map param) {
        UserEntity userentity = sessionmanager.getCurrentUser();
        Map orgMap = commonMangerExtService.findBusDeptById(userentity.getOrgId());
        param.put("orgId", orgMap.get("id"));
        if (null != param.get("customerPhone")) {
            param.put("customerPhone", desUtil.encrypt(param.get("customerPhone").toString()));
        }
        if (null == param.get("orderColumn")) {
            param.put("orderDir", "desc");
            param.put("orderColumn", "signTime");
        }
        return orderDao.orgOrderWithPage(param);
    }

    /**
     * 根据id获取销售订单
     *
     * @param id
     * @return
     */
    public Order selectByPrimaryKey(Long id) {
        return orderDao.selectByPrimaryKey(id);
    }

    /**
     * 根据订单id获取销售子订单列表和业务名称
     *
     * @return
     */
    public Map queryProductByOrderId(Long id) {
        Map map = new HashMap();
        map.put("id", id);
        List<Map> list = orderDao.queryProductByOrderId(map);
        StringBuffer productNames = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            productNames.append(list.get(i).get("procuctName"));
            if (i != list.size() - 1) {
                productNames.append("+");
            }
        }
        map.put("list", list);
        map.put("productNames", productNames.toString());
        return map;
    }

    /**
     * 确认移交
     */
    public void sureTransfer(Map params) {
        UserEntity userentity = sessionmanager.getCurrentUser();
        Map orgMap = commonMangerExtService.findBusDeptById(userentity.getOrgId());
        List<ProductOrder> list = productOrderDao.selectByOrderId(params);
        Map mapUser = commonMangerExtService.findOrg(userentity.getOrgId());
        Date date = new Date();
        for (int i = 0; i < list.size(); i++) {
            //修改生产订单
            ProductOrder po = list.get(i);

            //添加获取销售子订单参数
            params.remove("orderId");
            params.put("scProductOrderId", po.getId());
            Product product = productDao.findProductByOrderId(params);

            //非收证
            if (product.getBusinessProductCode().equals("BUS_YT_ZZ_ZS")) {
                continue;
            }
            po.setStatus(ScProductConstant.SC_ORDER_WAIT_ALLOT);
            po.setProductOrgId(Long.parseLong(params.get("orgId").toString()));
            po.setProductOrgName(params.get("addressDeptId").toString());
            po.setTransferTime(date);
            po.setTransferUserId(userentity.getId());
            po.setTransferUserName(userentity.getRealName() + "(" + userentity.getLoginName() + ")");
            po.setTransferUserOrgId(Long.parseLong(orgMap.get("id").toString()));
            po.setUpdaterId(userentity.getId());
            po.setUpdaterName(userentity.getRealName());
            po.setUpdaterOrgId(userentity.getOrgId());
            po.setUpdaterOrgName(mapUser.get("name").toString());
            po.setUpdateTime(date);

            po.setLatestEndNodeName("");
            po.setLatestEndNodeId(null);
            po.setLatestEndNodeTime(null);
            po.setFlowUserId(null);
            po.setFlowUserName("");
            po.setFlowUserOrgId(null);
            po.setFlowUserOrgName("");
            po.setReceiverId(null);
            po.setProductUserId(null);
			po.setProductUserOrgId(null);
			po.setCompletedTime(null);


            //修改流程id
            /*Map maps = new HashMap<>();
            maps.put("deptId", po.getProductOrgId());
            maps.put("businessCode", po.getBusinessProductCode());
            ProductNodeFlow node = nodeFlowDao.queryFlow(maps);
            ValidateUtils.isTrue(StringUtils.isNotEmpty(node), CommonExcption.class, "未查询到" + po.getProductOrgName() + "流程节点配置信息");
            po.setNodeFlowId(node.getId());*/
            //插入流程id
            String flowStr = flowService.getFlowNodeStr(product.getProductId().toString(), product.getBusinessTypeId(), po.getProductOrgId(),po.getBusinessProductCode());
            ValidateUtils.isTrue(StringUtils.isNotEmpty(flowStr), CommonExcption.class, "未查询到" + product.getBusinessTypeName() + "[" + product.getProductName() + "]流程节点的配置信息,请联系对应事业部后台负责人");
            List<Node> nodeList = flowService.getNodeByFlowContent(flowStr);
            Node nodeNew = new Node();
            Node nodeNew1 = new Node();
            for (Node node : nodeList) {
                if ("分配".equals(node.getName())) {
                    nodeNew = node;
                }
                if ("接单".equals(node.getName())) {
                    nodeNew1 = node;
                }
            }
            ValidateUtils.isTrue(StringUtils.isNotEmpty(nodeNew.getName()), CommonExcption.class, "未查询到[" + product.getProductName() + "]的分配节点的信息,请联系对应事业部后台负责人");
            ValidateUtils.isTrue(StringUtils.isNotEmpty(nodeNew1.getName()), CommonExcption.class, "未查询到到[" + product.getProductName() + "]的接单节点的信息,请联系对应事业部后台负责人");
            po.setFlowContent(flowStr);
            productOrderDao.updateByPrimaryKey(po);

            //移除协单人员
            Map map = new HashMap();
            map.put("scProductOrderId", po.getId());
            List<Assistant> assistants = assistantDao.query(map);
            for (int k = 0; k < assistants.size(); k++) {
                assistantDao.deleteByPrimaryKey(assistants.get(k).getId());
            }


            //修改生产订单超期
            ProductTimeStatus timestatus = producttimestatusdao.selectByPrimaryKey(po.getId());

//            try {
//                timestatus.setDistributionEndTime(DateUtils.dateAddDayJs(new Date(), 1));
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            if (node.getIsnaturalorworkday() == 1) {//工作日
//                Date nowDate = new Date();
//                String orderEndTime = cmsservice.findAfterDate(DateUtil.dateToString(nowDate, "yyyy-MM-dd HH:mm:ss"), node.getManagementCycle()) + " " + DateUtil.dateToString(nowDate, "HH:mm:ss");
//                timestatus.setOrderEndTime(DateUtil.stringToDate(orderEndTime, "yyyy-MM-dd HH:mm:ss"));
//            } else {
//                try {
//                    timestatus.setOrderEndTime(DateUtils.dateAddDayJs(new Date(), node.getManagementCycle()));
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//            }
            Node node = nodeNew;
            Map curentDept;//当前登录人部门
            userentity = sessionmanager.getCurrentUser();
            curentDept = this.commonMangerExtService.findOrg(userentity.getOrgId());
            Map map1 = flowService.getOderCycle(po);
            //写入分配节点
            Integer hours = 0;
            if (null != node) {
                timestatus.setNodeId(node.getCode());
                timestatus.setNodeName(node.getName());
                hours = node.getHandleDate();
                timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());
                timestatus.setNodeStartTime(new Date());
                long millisecond = 0l;
                long Days = (long) Math.ceil((double) node.getHandleDate() / 24);
                if (hours > 0) {
                    millisecond = Days * 24 * 3600 * 1000;
                }
                Date currentDate = null;
                //获取当前节点的配置的计算出的超期时间
                currentDate = commonService.getDateFromStartByType(new Date(),
                        (int) Math.ceil((double) node.getHandleDate() / 24), millisecond,
                        node.getIsNaturalorWorkday());
                currentDate = DateUtils.getDate(DateUtils.dateString(currentDate, "yyyy-MM-dd"), "yyyy-MM-dd");
                timestatus.setNodeEndTime(currentDate);
                timestatus.setNodeProcessTime((int) Math.ceil((double) hours / 24));
                timestatus.setNodeSuspendMillisecond(millisecond);
                timestatus.setDistributionEndTime(currentDate);
            }
            timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);//写入节点超期状态,默认不超期
            timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);
            timestatus.setCreaterId(userentity.getId());
            timestatus.setCreaterName(userentity.getRealName());
            timestatus.setCreateTime(new Date());
            timestatus.setOrderStartTime(new Date());
            timestatus.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            timestatus.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            double day = Double.valueOf(map1.get("processingCycle").toString()) / 24;
            int tday = (int) Math.ceil(day);
            Date orderEndTime = commonService.getDateFromStartByType(new Date(),
                    tday, (long) tday * 24 * 3600 * 1000,
                    (int) map1.get("cycleType"));
            timestatus.setOrderStartTime(new Date());
            timestatus.setOrderSuspendMillisecond((long) tday * 24 * 3600 * 1000);
            timestatus.setOrderProcessTimeType((int) map1.get("cycleType"));
            timestatus.setOrderProcessTime(tday);
            timestatus.setOrderEndTime(DateUtils.getDate(DateUtils.dateString(orderEndTime, "yyyy-MM-dd"), "yyyy-MM-dd"));
            producttimestatusdao.updateByPrimaryKey(timestatus);

            //修改销售子订单
            product.setProductOrgId(Long.parseLong(params.get("orgId").toString()));
            product.setProductOrgName(params.get("addressDeptId").toString());
            productDao.updateByPrimaryKey(product);

            //插入记录
            SystemRecord record = new SystemRecord();
            record.setOperateType("57");
            record.setRemarks("事业部移交");
            record.setSource(po.getOrderId().toString());
            record.setWorkTableName("");
            record.setWorkTableName(po.getScProductOrderNo());
            record.setOperaterId(userentity.getId());
            record.setOperaterName(userentity.getRealName() + "(" + userentity.getLoginName() + ")");
            record.setOperaterOrgId(Long.parseLong(orgMap.get("id").toString()));
            record.setOperateTime(date);
            record.setWorkId(po.getId());
            record.setWorkNo(po.getScProductOrderNo());
            OrganizationEntity operatedOrgan = organizationManager.findOrgEntityByOrgId(userentity.getOrgId());
            record.setId(DggKeyWorker.nextId());
            record.setOperaterOrgName(operatedOrgan.getName());

            systemRecordDao.insert(record);
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(po.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(po.getId());
            customerRecord.setTableNo(po.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE14);
            customerRecord.setCreaterId(userentity.getId());
            customerRecord.setContent("跨事业部移交");
            MQMessageSendUtil.ucMessageSend(customerRecord);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(po, null,  userentity);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(po, null,  userentity);
            String msgConent="您好，您的客户"+po.getCustomerName()+"订单"+po.getOrderNo()+"办理的"+po.getScProductOrderNo()+"业务，订单跨事业部移交给"+params.get("addressDeptId").toString()+"事业部,请及时确认处理";
            commonService.sendQgjMessage(po.getOrderId(),po.getBusinessTypeCode(),userentity.getId(),userentity.getRealName(),userentity.getLoginName(),msgConent);
        }
    }


    /**
     * 查询事业部订单待分配列表
     *
     * @param param
     * @return
     */
    public List<Map> orgOrderWaitAllotWithPage(Map param) {
        UserEntity userentity = sessionmanager.getCurrentUser();
        Map orgMap = commonMangerExtService.findBusDeptById(userentity.getOrgId());
        param.put("deptId", orgMap.get("id"));
        if (null != param.get("customerPhone")) {
            param.put("customerPhone", desUtil.encrypt(param.get("customerPhone").toString()));
        }
        if (null == param.get("orderColumn")) {
            param.put("orderDir", "desc");
            param.put("orderColumn", "t.create_time");
        }
        return productOrderDao.orgOrderWaitAllotWithPage(param);
    }

    /**
     * 查询事业部移交记录
     *
     * @param param
     * @return
     */
    public List<Map> orgOrderTransferRecordWithPage(Map param) {
        UserEntity userentity = sessionmanager.getCurrentUser();
        Map orgMap = commonMangerExtService.findBusDeptById(userentity.getOrgId());
        param.put("orgId", orgMap.get("id"));
        if (null != param.get("customerPhone")) {
            param.put("customerPhone", desUtil.encrypt(param.get("customerPhone").toString()));
        }
        if (null == param.get("orderColumn")) {
            param.put("orderDir", "desc");
            param.put("orderColumn", "b.operate_time");
        }
        return orderDao.orgOrderTransferRecordWithPage(param);
    }

    /**
     * 根据条件查询记录-导出
     *
     * @param params
     * @return
     */
    public List<OrderDataVo> findByParamsList(Map params) throws Exception {
        List<OrderDataVo> voList = new ArrayList<>();
        List<Map> srList = productOrderDao.exportOrderData(params);
        String[] transColum = {"originCode","status"};
        srList = translateUtil.translateList(transColum, srList);
        for (int i = 0; i < srList.size(); i++) {
            OrderDataVo vo = new OrderDataVo();

            vo.setSignTime(String.valueOf(srList.get(i).get("signTime") == null ? "" : srList.get(i).get("signTime")));
            vo.setSignUserName(String.valueOf(srList.get(i).get("signUserName") == null ? "" : srList.get(i).get("signUserName")));
            vo.setOrderNo(String.valueOf(srList.get(i).get("orderNo") == null ? "" : srList.get(i).get("orderNo")));
            vo.setContractNo(String.valueOf(srList.get(i).get("contractNo") == null ? "" : srList.get(i).get("contractNo")));
            vo.setMoney(String.valueOf(srList.get(i).get("money") == null ? "" : srList.get(i).get("money")));
            vo.setSignOrgName(String.valueOf(srList.get(i).get("signOrgName") == null ? "" : srList.get(i).get("signOrgName")));
            vo.setProductOrgName(String.valueOf(srList.get(i).get("productOrgName") == null ? "" : srList.get(i).get("productOrgName")));
            vo.setScProductOrderNo(String.valueOf(srList.get(i).get("scProductOrderNo") == null ? "" : srList.get(i).get("scProductOrderNo")));
            vo.setAllotUserName(String.valueOf(srList.get(i).get("allotUserName") == null ? "" : srList.get(i).get("allotUserName")));
            vo.setAllotDate(String.valueOf(srList.get(i).get("allotDate") == null ? "" : srList.get(i).get("allotDate")));
            vo.setReceiverName(String.valueOf(srList.get(i).get("receiverName") == null ? "" : srList.get(i).get("receiverName")));
            vo.setReceiveOrderDate(String.valueOf(srList.get(i).get("receiveTime") == null ? "" : srList.get(i).get("receiveTime")));
            vo.setCompanyName(String.valueOf(srList.get(i).get("companyName") == null ? "" : srList.get(i).get("companyName")));
            vo.setCustomerName(String.valueOf(srList.get(i).get("customerName") == null ? "" : srList.get(i).get("customerName")));
            vo.setProductName(String.valueOf(srList.get(i).get("productName") == null ? "" : srList.get(i).get("productName")));
            vo.setBusinessProductName(String.valueOf(srList.get(i).get("businessProductName") == null ? "" : srList.get(i).get("businessProductName")));
            vo.setStatus(String.valueOf(srList.get(i).get("status") == null ? "" : srList.get(i).get("status")));
            vo.setLatestEndNodeName(String.valueOf(srList.get(i).get("latestEndNodeName") == null ? "" : srList.get(i).get("latestEndNodeName")));

            voList.add(vo);
        }
        return voList;
    }
    /*
     * @Author zsx
     * @Date 2018-11-13 10:11:28
     * @Description 根据订单编号查询订单生产id
     * @param scOrderNo 订单编号
     * @return List<Long>
     */
    public List<Long> findOrderIdByScOrderNo(String scOrderNo){
        Map<String,String> params = new HashMap<String, String>(){{
            put("orderOver",ScProductConstant.SC_ORDER_OVER);
            put("orderOverOverdue",ScProductConstant.SC_ORDER_OVER_OVERDUE);
            put("orderOverForce",ScProductConstant.SC_ORDER_OVER_FORCE);
            put("orderJunctions",ScProductConstant.SC_ORDER_JUNCTIONS);
            put("orderSuspend",ScProductConstant.SC_ORDER_SUSPEND);
            put("orderChargebackDsh",ScProductConstant.SC_ORDER_CHARGEBACK_DSH);
            put("orderChargebackTdbh",ScProductConstant.SC_ORDER_CHARGEBACK_TDBH);
            put("orderFinishedChargeback",ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK);
            put("scOrderNo",scOrderNo);
        }};
       return productOrderDao.selectOrderIdByScOrderNo(params);
    }

}
